package com.rongke.web.controller.login;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.model.User;
import com.rongke.service.UserService;
import com.rongke.utils.DateUtils;
import com.rongke.utils.Md5;
import com.rongke.utils.UserIdGenerator;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * @UserController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value = "/api/auth")
@Transactional
public class UserLoginController {
    private Logger      log = Logger.getLogger(UserLoginController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private SessionDAO  sessionDAO;

    /**
     * @登录
     * @param phone
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResp login(HttpServletRequest request, String phone, String authCode) {
        try {
            log.debug("Login normal user, phone=" + phone + ",authCode =" + authCode);

            // 首先验证短信校验码 TODO:待短信接口到位后修改

            // 重新生成token
            String newToken = UUID.randomUUID().toString();
            newToken = newToken.replaceAll("-", "");
            String md5Token = Md5.md5Encode(newToken);

            // 判断当前手机号是否存在，如果不存在，先自动注册
            User user = userService.selectByPhone(phone);
            if (null == user) {
                // 用户不存在，注册
                user = new User();
                user.setUserId(UserIdGenerator.getNewUserId());
                user.setPhone(phone);
                user.setToken(md5Token);
                user.setGmtLogin(new Date());
                user.setAlias(phone);// 注册时，用手机号代替别名
                userService.insert(user);
            } else {
                user.setToken(md5Token);
                user.setGmtLogin(new Date());
                userService.updateById(user);
            }

            Subject subject = SecurityUtils.getSubject();
            // UsernamePasswordToken token = new UsernamePasswordToken(phone,
            // "FixedPassword");
            Session session = subject.getSession();
            session.setAttribute("user", user);
            System.out.println("startTimetamp:"
                               + DateUtils.timeDate(session.getStartTimestamp(),
                                   DateUtils.YYYY_MM_DD_HH_MM_SS));
            System.out.println("lastAccessTime:"
                               + DateUtils.timeDate(session.getLastAccessTime(),
                                   DateUtils.YYYY_MM_DD_HH_MM_SS));

            request.getSession().setAttribute("userId", user.getUserId());

            Map<String, String> dataResult = new HashMap<String, String>();
            dataResult.put("phone", user.getPhone());
            dataResult.put("token", newToken);
            dataResult.put("userId", user.getUserId());
            return JsonResp.ok(dataResult);
        } catch (Exception e) {
            return JsonResp.fa(null);
        }
    }

    /**
     * 发送验证码
     * 
     * @param phone
     * @return
     */
    @RequestMapping(value = "/sendAuthCode", method = RequestMethod.POST)
    public JsonResp sendAuthCode(String phone) {
        log.debug("send Auth Code, phone = " + phone);

        String authCode = "123456";// TODO:暂时写死，待短信接口到位后再修改
        return JsonResp.ok();
    }
}
